﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Wpf2.Models;
using Wpf2.ViewModels;
using WPFServices;

namespace Wpf2.Views
{
    /// <summary>
    /// Interaction logic for AddProductType1.xaml
    /// </summary>
    public partial class AddProductType1
    {
        NotifiableCollection<Catalogs> _catalogs;
        NotifiableCollection<Unit> _units;
        NotifiableCollection<Products> _products;
        IList<Products> _productFirstLoad;
        public AddProductType1()
        {
            InitializeComponent();
            LoadingInit();
        }

        private void DtgDanhmucRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            if (e.EditAction != DataGridEditAction.Commit) return;
            var p = e.Row.DataContext as Products;
            var action = _products.Where(x => p != null && x.ProductIdAuto == p.ProductIdAuto).Select(x =>x.ProductIdAuto).SingleOrDefault();


                if (action == 0)
                {
                    if (p != null)
                    {
                        var dt = new DETAILS_PRODUCTS
                                     {
                                         ID_UNITS = p.UnitId,
                                         COST_PRICES = p.CostPrice,
                                         SELL_PRICE = p.SellPrice,
                                         INVENTORY_COUNT = p.InventoryCount
                                     };
                        var pr = new PRODUCT
                                     {
                                         ID_PRO = p.ProductId,
                                         NAME_PRO = p.ProductName,
                                         DESCRIPTIONS = p.ProductDescription,
                                         ID_CATALOG = p.CatalogId,
                                         DETAILS_PRODUCTS = dt,

                                     };
                        try
                        {
                            var idPro = WPFServices.Services.Products.CreateProduct(pr);
                            var firstOrDefault = _products.FirstOrDefault(x => x.ProductIdAuto == 0);
                            if (firstOrDefault != null)
                                firstOrDefault.ProductIdAuto = idPro;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "Bạn phải chọn danh mục, chọn đơn vị");
                            _products.Remove(p);

                        }
                    }
                }
                else
                {
                    if (p != null)
                    {
                        var currentP = WPFServices.Services.Products.GetProduct(p.ProductIdAuto);
                        var dt = new DETAILS_PRODUCTS
                                     {
                                         ID_DETAILS = currentP.DETAILS_PRODUCTS.ID_DETAILS,
                                         ID_UNITS = p.UnitId,
                                         COST_PRICES = p.CostPrice,
                                         SELL_PRICE = p.SellPrice,
                                         INVENTORY_COUNT = p.InventoryCount
                                     };
                        var pr = new PRODUCT
                                     {
                                         ID_PRO_AUTO = p.ProductIdAuto,
                                         ID_PRO = p.ProductId,
                                         NAME_PRO = p.ProductName,
                                         DESCRIPTIONS = p.ProductDescription,
                                         ID_CATALOG = p.CatalogId,
                                         DETAILS_PRODUCTS = dt,

                                     };
                        try
                        {
                            WPFServices.Services.Products.UpdateProduct(pr);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            
        }

        private void DtgProductLoadingRow(object sender, DataGridRowEventArgs e)
        {
            if (e != null) e.Row.Header = (e.Row.GetIndex() + 1).ToString(CultureInfo.InvariantCulture);
        }

        private void BtnAddCatalogClick(object sender, RoutedEventArgs e)
        {
            var fDM = new FormManageCategory();
            fDM.ShowDialog();
            LoadingInit();
        }
        private void LoadingInit()
        {
            try
            {
                var listUn = WPFServices.Services.Units.GetListUnits().Select(x => new Unit
                    {
                        UnitID = x.ID_UNIT,
                        UnitName = x.NAME_UNIT,
                        UnitNote = x.NOTES_UNIT
                    });
                _units = new NotifiableCollection<Unit>();
                foreach (var u in listUn)
                {
                    _units.Add(u);
                }
                
                //Load Câtlog
                var listCa = WPFServices.Services.Catalogs.GetListCatalogs().Select(x => new Catalogs
                {
                    IDCatalog = x.ID_CATALOG,
                    CatalogName = x.NAME_CATALOG,
                    CatalogNotes = x.NOTES_CATALOG
                });
                _catalogs = new NotifiableCollection<Catalogs>();
                foreach (var c in listCa)
                {
                    _catalogs.Add(c);
                }
                //load product
                _products = new NotifiableCollection<Products>();
                _productFirstLoad = new List<Products>();
                var listPro = WPFServices.Services.Products.GetListProducts().Select(p => new Products
                {
                    ProductIdAuto = p.ID_PRO_AUTO,
                    ProductId = p.ID_PRO,
                    ProductName = p.NAME_PRO,
                    ProductDescription = p.DESCRIPTIONS,
                    CostPrice = p.DETAILS_PRODUCTS.COST_PRICES ?? 0,
                    SellPrice = p.DETAILS_PRODUCTS.SELL_PRICE ?? 0,
                    InventoryCount = p.DETAILS_PRODUCTS.INVENTORY_COUNT ?? 0,
                    CatalogId = p.ID_CATALOG,
                    UnitId = p.DETAILS_PRODUCTS.ID_UNITS,

                });
                foreach (var p in listPro)
                {
                    _products.Add(p);
                    _productFirstLoad.Add(p);
                }
                dtgProduct.DataContext = _products;

                dtgcmbUnit.ItemsSource = _units;
                dtgcmbCatalog.ItemsSource = _catalogs;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void TxtIDProTextChanged(object sender, TextChangedEventArgs e)
        {
            string searchString = txtIDPro.Text;
            cmbSearchByID.Items.Clear();
            foreach (var pro in _products)
            {
                if (pro.ProductId.IndexOf(searchString, StringComparison.Ordinal) < 0 || string.IsNullOrEmpty(searchString)) continue;
                var cbmItem = new ComboBoxItem {Content = pro.ProductId, Tag = pro.ProductIdAuto};
                cmbSearchByID.Items.Add(cbmItem);
            }
            cmbSearchByID.IsDropDownOpen = cmbSearchByID.HasItems;
        }

        private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox = sender as ComboBox;
            if (comboBox != null && comboBox.SelectedItem != null)
            {
                var id = (sender as ComboBox).SelectedItem as ComboBoxItem;
                if (id != null) txtIDPro.Text = id.Content.ToString();
                btnSearchbyid.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
            }
            btnSearchbyid.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
        }

        private void BtnSearchbyidClick(object sender, RoutedEventArgs e)
        {

            var listP = SearchProId(txtIDPro.Text);
            _products.Clear();
            foreach (Products p in listP)
            {
                _products.Add(p);
            }
        }

        private void CmbSearchByNameSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //ComboBoxItem cmbItem = (ComboBoxItem)cmbSearchByName.SelectedItem;
            var comboBox = sender as ComboBox;
            if (comboBox == null || comboBox.SelectedItem == null) return;
            var name = (sender as ComboBox).SelectedItem as ComboBoxItem;
            if (name != null) txtSearchbyName.Text = name.Content.ToString();
            btnSearchbyName.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
        }

        private void BtnSearchbyNameClick(object sender, RoutedEventArgs e)
        {
           var listP=SearchPro(txtSearchbyName.Text);
            _products.Clear();
            foreach (Products p in listP)
            {
                _products.Add(p);
            }
        }

        private IEnumerable<Products> SearchPro(string value)
        {
            var listPro=_productFirstLoad.Where(x => x.ProductName.ToUpper().Contains(value.ToUpper().Trim()));
            if (!string.IsNullOrEmpty(value))
            {
                listPro = listPro.Where(x => x.ProductName.ToUpper().Contains(value.ToUpper().Trim()));
            }
            return listPro.ToList();
        }

        private IEnumerable<Products> SearchProId(string value)
        {
            var listPro = _productFirstLoad.Where(x => x.ProductId.ToUpper().Contains(value.ToUpper().Trim()));
            if (!string.IsNullOrEmpty(value))
            {
                listPro = listPro.Where(x => x.ProductId.ToUpper().Contains(value.ToUpper().Trim()));
            }
            return listPro.ToList();
        }

        private void TxtSearchbyNameTextChanged(object sender, TextChangedEventArgs e)
        {

            var searchString = txtSearchbyName.Text;
            cmbSearchByName.Items.Clear();
            foreach (var cbmItem in from pro in _productFirstLoad where pro.ProductName.ToUpper().IndexOf(searchString.ToUpper(), StringComparison.Ordinal) >= 0 && !string.IsNullOrEmpty(searchString) select new ComboBoxItem {Content = pro.ProductName, Tag = pro.ProductIdAuto})
            {
                cmbSearchByName.Items.Add(cbmItem);
            }
            cmbSearchByName.IsDropDownOpen = cmbSearchByName.HasItems;
        }

        private void BtnDeleteClick(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null) return;
            var p = button.DataContext as Products;
            if (p == null || p.ProductIdAuto == 0) return;
            try
            {
                if (p.InventoryCount > 0)
                {
                    MessageBox.Show("Sản phẩm còn trong kho nên không thể ẩn.");
                }
                else {
                    WPFServices.Services.Products.ChangeStatus(p.ProductIdAuto, false);
                    _products.Remove(p);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BtnShowProductHiddenClick(object sender, RoutedEventArgs e)
        {
            var f = new FormProductHidden();
            f.ShowDialog();
        }

        private void TxtIDProPreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnSearchbyid.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
            }
        }

        private void TxtSearchbyNamePreviewKeyUp(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                btnSearchbyName.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
            }
        }

        private void BtnShowUserClick(object sender, RoutedEventArgs e)
        {
            var f = new ManagePassword();
            f.ShowDialog();
        }

        private void DtgProductCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var p = e.Row.Item as Products;
            if (e.Column.DisplayIndex != 1) return;
            if (p == null) return;
            var id = p.ProductId;
            var listPro = WPFServices.Services.Products.GetListProducts();

            var action = _products.Where(x => x.ProductIdAuto == p.ProductIdAuto).Select(x => x.ProductIdAuto).SingleOrDefault();
            if (action == 0)
            {
                if (listPro.All(x => x.ID_PRO != id)) return;
                MessageBox.Show("Mã người dùng đã tồn tại.");
                p.ProductId = string.Empty;
            }
            else
            {
                var currentC = WPFServices.Services.Products.GetProduct(p.ProductIdAuto);
                if (currentC.ID_PRO == p.ProductId) return;

                if (listPro.All(x => x.ID_PRO != id)) return;
                MessageBox.Show("Mã người dùng đã tồn tại.");
                p.ProductId = string.Empty;
            }

        }

        private void chkDahoacuong_Checked(object sender, RoutedEventArgs e)
        {

        }


    }
}
